<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*------------------------------------------------------------------------
 * socket 客服端类
 * 作者：seven
 * qq：397109515
 *------------------------------------------------------------------------
 */
class Socket_client{
	private $CI;
	private $socket;//socket对象
	private $address = 'localhost';//socket地址
	private $service_port = '12345';//socket 服务器端口
	private $socket_service_message_len = 8192;//接受的数据长度
	private $socket_message_len = false;
	public function __construct()
	{
		$this->CI =& get_instance();
		
	}
	/*
	 * 发送数据
	 */
	public function init()
	{
            $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            $this->socket_error($this->socket);
            $this->socket_connect();
            $this->socket_write();
            $data = $this->socket_read();
            $this->socket_close();	
            return $data;
	}
	/*
	 * 连接socket
	 * return 
	 */
	protected function socket_connect()
	{
		return socket_connect($this->socket, $this->address, $this->service_port);
	}
	
	/*
	 * 发送socket信息
	 * return
	 */
	protected function socket_write()
	{
		if($this->socket_message_len == false)
		{
			$this->socket_message_len = strlen($this->socket_message);
		}
		return socket_write($this->socket, $this->socket_message, $this->socket_message_len);
	}

	/*
	 * 接受socket服务器返回的信息
	 * return
	 */
	protected function socket_read()
	{
		return socket_read($this->socket, $this->socket_service_message_len);
	}
	/*
	 * 关闭socket
	 * return
	 */
	protected function socket_close()
	{
		return socket_close($this->socket);
	}
	/*
	 * 传入需要连接的地址
	 * @param string address 需要传入的地址
	 * @param 
	 */
	public function set_address($address)
	{
		//$this->socket_error((!preg_match(PREG_IP,$address) && !preg_match(PREG_URL,$address)),'地址错误');
		$this->address = $address;
	}
	/*
	 * 传入需要传送的数据的长度
	 * @param int  socket_message_len 需要传入的地址
	 * @param 
	 */
	public function set_socket_message_len($socket_message_len)
	{
		$this->socket_message_len = $socket_message_len;
	}
	/*
	 * 传入需要连接的端口
	 * @param string address 需要传入的端口
	 * @param 
	 */
	public function set_port($service_port)
	{
		$this->socket_error((!is_numeric($service_port) || $service_port > 65536 || $service_port < 65536),'端口地址错误');
		$this->service_port = $service_port;
	}
	/*
	 * 传入需要发送的消息
	 * @param string socket_message 需要传入的地址
	 * @param 
	 */
	public function set_socket_message($socket_message)
	{
		$this->socket_message = $socket_message;
	}
	/*
	 * 抛出错误
	 * @param bool type 
	 * @param string data 提示的信息
	 * return
	 */
	protected function socket_error($type,$data = false)
	{
		if($type ===  false)
		{
			if($data === false)
			{
				throw new Exception(socket_strerror(socket_last_error()));
			}
			else
			{
				throw new Exception($data);
			}
		}
	}
}